import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login'
import home from '../views/home'
import find from '@/views/home/find'
import my from '@/views/home/my'
import questions from '@/views/home/questions'
import info from '@/views/info'
import editInfo from '@/views/info/editInfo'
import shareList from '@/views/home/shareList'

import search from '@/views/home/shareList/search.vue'

import shareDetail from '@/views/home/shareList/shareDetail.vue'

import interview from '@/views/home/questions/interview.vue'
import company from '@/views/home/company'

import { getLocal } from '@/utils/local.js'
import store from '../store/index'
import { apiGetInfo } from '@/api/au.js'
import { Toast } from 'vant'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: login },
  {
    path: '/home',
    component: home,
    children: [
      { path: '/find', component: find },
      {
        path: '/my',
        component: my,
        meta: {
          needLogin: true
        }
      },
      {
        path: '/questions',
        component: questions,
        meta: {
          needLogin: true
        }
      },
      {
        path: '/company',
        component: company
      }
    ]
  },
  {
    path: '/info',
    component: info,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/editInfo',
    component: editInfo,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/shareList',
    component: shareList
  },
  {
    path: '/search',
    component: search
  },
  {
    path: '/shareDetail/:id',
    component: shareDetail
  },
  {
    path: '/interview',
    component: interview,
    meta: {
      needLogin: true
    }
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach(async (to, from, next) => {
  // console.log(to)
  const needLogin = to.meta.needLogin
  if (!needLogin) {
    next()
  } else {
    const token = getLocal('token')
    if (token) {
      const userInfo = store.state.userInfo
      if (userInfo) {
        next()
      } else {
        const res = await apiGetInfo()
        store.commit('setUserInfo', res.data)
        next()
      }
    } else {
      Toast.fail('请先登录')
      router.push('/login?redirect=' + to.path)
    }
  }
})
export default router
